package com.dodoke.cake.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dodoke.cake.bean.CakeProduct;
import com.dodoke.cake.bean.Classification;
import com.dodoke.cake.service.ProductListService;
import com.dodoke.cake.utils.PageUtil;
import com.dodoke.cake.utils.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class ProductController {
    @Autowired
    private ProductListService productListService;


    @RequestMapping("/cake_list")
    public String cake_list(){
        return "cake_list";
    }

    @RequestMapping("/cake_add_second")
    public String cake_add_second() {
        return "/cake_add_second";
    }

    /**
     * 商品详情
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/toCakeInfo")
    public String cake_info(Model model, int id){

        CakeProduct cakeProduct = productListService.getCakeInfo(id);
        System.out.println(cakeProduct.getCakeName());
        model.addAttribute("cakeInfo", cakeProduct);

        return "cake_info";
    }

    /**
     * 获取当前页面数据
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping("/getPageData")
    public Result getPageData(@RequestBody Map<String,String> map){
        System.out.println(map.get("nextPage"));
        String currentPage = map.get("nextPage");
        /*if(currentPage == null) {
            currentPage = "1";
        }*/
        int count = this.productListService.getAllProductCount();
        System.out.println(count);
        int allPageNum = PageUtil.getAllPage(count, 20);
        int fromWhichData = PageUtil.getFromWhichData(Integer.parseInt(currentPage), 20);
        List<CakeProduct> list = this.productListService.getCurrentPageData(fromWhichData,20);
        Result res = new Result();
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("allPage", allPageNum);
        m.put("data", list);
        res.result = m;
        return res;
    }


    @GetMapping("ToEdit")
    public String toEdit(Model model,  @Param("id") int id) {
        CakeProduct cakeProduct = productListService.getCakeInfo(id);
        model.addAttribute("cakeInfo", cakeProduct);
        model.addAttribute("id", id);
        return "cake_add";
    }


    /**
     * 编辑商品
     */
    @RequestMapping("/editCake")
    public String editCake(@RequestParam("picUrl") MultipartFile file,
                           @RequestParam("cakeName") String cakeName, @RequestParam("state") String state,
                           @RequestParam("cakeType") String cakeType, @RequestParam("taste") String taste, @RequestParam("sweetness") String sweetness,
                           @RequestParam("price") String price, @RequestParam("weight") String weight, @RequestParam("size") String size,
                           @RequestParam("ingredient") String ingredient, @RequestParam("id") String id, @RequestParam("imageUrl") String picUrl,
                           HttpServletRequest request) throws IOException {

        CakeProduct cp = new CakeProduct();
        if (!file.isEmpty()) {

            String path = request.getServletContext().getRealPath("/WEB-INF/assets/download/images");
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            File filePath = new File(path, uuid + "-" + fileName);
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            file.transferTo(filePath);
            cp.setPicUrl("/assets/download/images/"+ uuid + "-" + fileName);
            System.out.println("/assets/download/images/"+ uuid + "-" + fileName);
        }else{
            cp.setPicUrl(picUrl);
        }
        cp.setId(Integer.parseInt(id));
        cp.setCakeName(cakeName);
        cp.setState(state);
        cp.setCakeType(cakeType);
        cp.setTaste(taste);
        cp.setSweetness(sweetness);
        cp.setPrice(Float.parseFloat(price));
        cp.setWeight(Double.parseDouble(weight));
        cp.setSize(Integer.parseInt(size));
        cp.setIngredient(ingredient);
        this.productListService.upCakeProduct(cp);
        //return "cake_list";
        return "redirect:cake_list";
    }


    @ResponseBody
    @RequestMapping("/productDelete")
    public String productDelete(@RequestBody Map<String,String> map) {
        System.out.println(map.get("id"));
            this.productListService.deleteCake(Integer.parseInt(map.get("id")));
            return "";
    }

    @ResponseBody
    @RequestMapping("/productBatchDelete")
    public String productBatchDelete(@RequestBody Map<String,List<String>> map) {
        System.out.println(map.get("ids").size());
        List<String> list = map.get("ids");
        for(int i = 0;i<list.size();i++) {
            this.productListService.deleteCake(Integer.parseInt(list.get(i)));
        }
        //this.productListService.deleteCake(Integer.parseInt(map.get("id")));
        return "";
    }



    @RequestMapping("/cakeAdd")
    public String cakeAdd(@RequestParam("picUrl") MultipartFile file, @RequestParam("cakeName") String cakeName, @RequestParam("state") String state,
                          @RequestParam("cakeType") String cakeType, @RequestParam("taste") String taste, @RequestParam("sweetness") String sweetness,
                          @RequestParam("price") String price, @RequestParam("weight") String weight, @RequestParam("size") String size,
                          @RequestParam("ingredient") String ingredient,
                          HttpServletRequest request) throws IOException {

        CakeProduct cp = new CakeProduct();
        if (!file.isEmpty()) {
            String path = request.getServletContext().getRealPath("/WEB-INF/assets/download/images");
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            File filePath = new File(path, uuid + "-" + fileName);
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            file.transferTo(filePath);
            cp.setPicUrl("/assets/download/images/"+ uuid + "-" + fileName);
            //System.out.println("/assets/download/images/"+ uuid + "-" + fileName);
        }
       // cp.setId(Integer.parseInt(id));
        cp.setCakeName(cakeName);
        cp.setState(state);
        cp.setCakeType(cakeType);
        cp.setTaste(taste);
        cp.setSweetness(sweetness);
        cp.setPrice(Float.parseFloat(price));
        cp.setWeight(Double.parseDouble(weight));
        cp.setSize(Integer.parseInt(size));
        cp.setIngredient(ingredient);
        this.productListService.insertCake(cp);
        return "redirect:cake_list";
    }
}
